package codeTop;

import java.util.ArrayList;
import java.util.List;

public class q54 {
    public List<Integer> spiralOrder(int[][] matrix) {
        int status = 0;
        int m = matrix.length;
        int n = matrix[0].length;
        int num = 0;
        int i = 0;
        int j = 0;
        List<Integer> res = new ArrayList<>();
        while (true) {
            res.add(matrix[i][j]);
            matrix[i][j] = 101;
            num++;
            if (num == m * n) {
                break;
            }
            if (status == 0) {
                if (j + 1 < n && matrix[i][j + 1] != 101) {
                    j = j+1;
                }else {
                    status = 1;
                    i = i+1;
                }
            } else if (status == 1) {
                if (i + 1 < m && matrix[i+1][j] != 101) {
                    i = i+1;
                }else {
                    status = 2;
                    j = j-1;
                }
            } else if (status == 2) {
                if (j - 1 >= 0 && matrix[i][j - 1] != 101) {
                    j = j-1;
                }else {
                    status = 3;
                    i = i-1;
                }
            }else {
                if (i - 1 >= 0 && matrix[i-1][j] != 101) {
                    i = i-1;
                }else {
                    status = 0;
                    j = j+1;
                }
            }
        }
        return res;
    }
}
